#!/usr/bin/env python

import os
import sys

DIRNAME = os.path.dirname(__file__)

_parent = lambda x: os.path.normpath(os.path.join(x, '..'))
SHOP_PARENT_DIRNAME = _parent(DIRNAME)

if not SHOP_PARENT_DIRNAME in sys.path:
    sys.path.append(SHOP_PARENT_DIRNAME)

os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from product.models import *   

def update_storage():
    import csv
    from django.contrib.sites.models import Site
    
    reader = csv.reader(open(settings.DATA_FILE_NAME), delimiter=';')
    site = Site.objects.get_current()
    cats_hash = {} # {1c_code:[site_cat1, site_cat2]}
    update_category(reader, site, cats_hash)
    update_product(reader, site, cats_hash)

def update_category(reader, site, cats_hash):
    for row in reader:
        ln = len(row)
        if ln == 0: break
        code = row[0].strip()
        parent_code = row[1].strip()
        name = row[2].strip()
        cat_1c_code = row[3].strip()
        if cat_1c_code in cats_hash:
            cats_hash[cat_1c_code].append(code)
        else:
            cats_hash[cat_1c_code] = [code]
        try:
            cat = Category.objects.get(site=site, slug=code)
            if cat.name <> name:
                cat.name = name
                cat.save()
        except ObjectDoesNotExist:
            cat = Category(site = site, slug = code, name = name)
            if len(parent_code) > 0:
                cat.parent = Category.objects.get(slug__iexact=parent_code)
            cat.save()
    
def update_product(reader, site, cats_hash):
    for row in reader:
        if row.count < 4:
            print 'Product line must contains 4 parts ParentCode,Code,Name,ItemsInStock,Price. Line [%s]' % row
            continue
        try:
            parent_code = row[0].strip()
            code = row[1].strip()
            name = row[2].strip()
            items_in_stock = int(row[3].strip())
            new_price = row[4].strip()
        except:
            print "Error, row: %s" % row
            continue
        try:
            product = Product.objects.get(site=site, slug=code)
            #if product.name <> name or product.items_in_stock <> items_in_stock:
            product.name = name
            product.items_in_stock = items_in_stock;
            if product.items_in_stock == 0:
                product.active = False                
            product.save()

            prices = product.price_set.exclude(
                expires__isnull=False,
                expires__lt=datetime.date.today()).filter(quantity__lte=1) # simple quantity, always = 1
            
            if len(prices) == 0:
                price = Price(product=product, price = new_price)
                price.save()
            else:
                price = prices[0]
                if price.price <> new_price:
                    price.price = new_price
                    price.save()
            #todo: if change category for product do change category
        except ObjectDoesNotExist:
            if parent_code in cats_hash:
                product = Product (site = site, slug = code, name = name, items_in_stock = items_in_stock)
                if product.items_in_stock == 0:
                    product.active = False
                product.save()
                for site_cat_code in cats_hash[parent_code]:
                    product.category.add(Category.objects.get(slug=site_cat_code))
                price = Price(product=product, price = new_price)
                price.save()
            else:
                print "Error %s" % row

update_storage()

